package com.michael.study.component.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.michael.study.component.R
import kotlinx.android.synthetic.main.activity_service.*

class ServiceActivity : AppCompatActivity(), View.OnClickListener {

    private class MessengerHandler : Handler() {

        override fun handleMessage(msg: Message) {
            when(msg.what) {
                2000 -> {
                    Log.d("lgq", "receive a msg from server: ")
                }
            }
        }
    }


    private var mServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(MyService.TAG, "onServiceDisconnected: ")
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d(MyService.TAG, "onServiceConnected: ")
        }

    }

    private lateinit var mMessenger: Messenger
    private var mGetReplayMessenger = Messenger(MessengerHandler())

    private var mMessengerConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {

            mMessenger = Messenger(service)
            var msg = Message.obtain(null,1000)
            var bundle = Bundle()
            bundle.putString("msg","Hello, this is client")
            msg.data = bundle
            msg.replyTo = mGetReplayMessenger

            try {
                mMessenger.send(msg)
            } catch (e: RemoteException) {

            }

        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service)
        btn_start.setOnClickListener(this)
        btn_bind.setOnClickListener(this)
        btn_messenger.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_start -> {
                var intent = Intent(this, MyService::class.java)
                startService(intent)
            }

            R.id.btn_bind -> {
                var intent = Intent(this, MyService::class.java)
                bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
            }

            R.id.btn_messenger -> {
                var intent = Intent(this, MessengerService::class.java)
                bindService(intent, mMessengerConnection, Context.BIND_AUTO_CREATE)
            }
        }

    }
}